package com.tts.service;

import com.tts.entity.Book;
import com.tts.repository.BookRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class BookService {

    @Autowired
    private BookRepository bookRepository;

    public Page<Book> findAll(Pageable pageable) {
        return bookRepository.findAll(pageable);
    }

    public Book findById(Long id) {
        return bookRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("Book not found"));
    }

    @Transactional
    public Book create(Book book) {
        if (bookRepository.existsByIsbn(book.getIsbn())) {
            throw new RuntimeException("ISBN already exists");
        }
        return bookRepository.save(book);
    }

    @Transactional
    public Book update(Long id, Book book) {
        Book existingBook = findById(id);
        
        if (!existingBook.getIsbn().equals(book.getIsbn()) 
                && bookRepository.existsByIsbn(book.getIsbn())) {
            throw new RuntimeException("ISBN already exists");
        }

        book.setId(id);
        return bookRepository.save(book);
    }

    @Transactional
    public void delete(Long id) {
        bookRepository.deleteById(id);
    }
} 